package woyaogexing

import ( //必需
	// "fmt"

	"github.com/henrylee2cn/pholcus/common/goquery"

	//DOM解析
	//信息输出
	// "regexp"

	"github.com/henrylee2cn/pholcus/app/downloader/request"
	. "github.com/henrylee2cn/pholcus/app/spider" //必需
	// "github.com/henrylee2cn/pholcus/logs"
	// . "github.com/henrylee2cn/pholcus/app/spider/common"          //选用
	// net包
	// "net/http" //设置http.Header
	// "net/url"
	// 编码包
	// "encoding/xml"
	// "encoding/json"
	// 其他包
	// "math"
	// "time"
	// "strings"
)

func init() {
	headimg.Register()
}

var headimg = &Spider{
	Name:            "woyaogexing/headimg",
	Description:     "woyaogexing/headimg",
	EnableCookie:    true,
	NotDefaultField: false,
	Namespace:       nil,
	SubNamespace:    nil,
	RuleTree: &RuleTree{
		Root: func(ctx *Context) {
			ctx.AddQueue(&request.Request{Url: woyaogexing_host + "/touxiang/index.html", Rule: "index"})

		},
		Trunk: map[string]*Rule{
			"index": {
				ItemFields: []string{
					"str",
				},
				ParseFunc: func(ctx *Context) {
					dom := ctx.GetDom()

					dom.Find(".pageNum.wp .page>a").Each(func(i int, a *goquery.Selection) {

						// ctx.Output(map[int]interface{}{
						// 	0:a.Text(),
						// })

						if woyaogexing_env != "development" && "下一页" == a.Text() {
							// ctx.Output(map[int]interface{}{
							// 	0:a.Text(),
							// })
							if href, ok := a.Attr("href"); ok {
								ctx.AddQueue(&request.Request{
									Url:  woyaogexing_host + href,
									Rule: "index",
								})
							}
						}

					})

					dom.Find(".txList").Each(func(i int, txList *goquery.Selection) {
						imgTitle := txList.Find(".imgTitle")

						if nil == imgTitle {
							return
						}

						if href, ok := imgTitle.Attr("href"); ok {
							ctx.AddQueue(&request.Request{
								Url:  woyaogexing_host + href,
								Rule: "nv",
							})
						}
					})
				},
			},
			"nv": {
				ItemFields: []string{
					"imgurl",
				},
				ParseFunc: func(ctx *Context) {
					dom := ctx.GetDom()

					dom.Find("ul.artCont.cl>li").Each(func(i int, li *goquery.Selection) {
						img := li.Find("img")

						// if nil == img {
						// 	return
						// }

						if src, ok := img.Attr("src"); ok {
							// ctx.AddQueue(&request.Request{
							// 	Url:  src,
							// 	Rule: "downloadnv",
							// })
							// ctx.Output(map[int]interface{}{
							// 	0: src,
							// })
							ctx.Output(map[int]interface{}{
								0: src,
							})
						}

					})
				},
			},
			"downloadnv": {
				ParseFunc: func(ctx *Context) {
					ctx.FileOutput()
				},
			},
		},
	},
}
